﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Electure.DAL
{
    public abstract class BaseModel
    {
        public int ID { get; set; }
    }
    public abstract class BaseRepository<T>:IDisposable 
        where T : BaseModel       
    {
        protected IDbConnection connection;

        internal BaseRepository()
        {
            connection = new SqlConnection(
                ConfigurationManager
                .ConnectionStrings["electureConnection"]
                .ConnectionString);

            connection.Open();
        }
        public void Dispose()
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }

        protected abstract int create(T instance);
        public virtual int Create(T instance)
        {
            try
            {
                if (create(instance) != 1)
                    return -1;
                
                return (int)connection.Query("SELECT @@IDENTITY newid").FirstOrDefault().newid;
            }
            catch (Exception e)
            {
                return -1;
            }
        }
        public abstract bool Update(T instance);
        public abstract bool Delete(int id);
        public abstract List<T> GetAll();
        public virtual T GetById(int id)
        {
            return GetAll().Where(item => item.ID == id).SingleOrDefault();
        }
    }
}
